package logic

import (
	"context"
	"encoding/json"
	"time"
	"zk/product_zy17/models/cache"
	"zk/product_zy17/models/mysql"
	"zk/product_zy17/productRpc/internal/svc"
	"zk/product_zy17/productRpc/productRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProductLogic {
	return &ListProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListProductLogic) ListProduct(in *productRpc.ListProductRequest) (*productRpc.ListProductResponse, error) {
	// todo: add your logic here and delete this line

	var goods []mysql.Product

	cacheData, _ := cache.RedisDB.Get(l.ctx, "listGoods").Result()
	if cacheData == "" {
		query := mysql.DB.Order("created_at,price asc")

		if in.Title != "" {
			query = query.Where("title=?", in.Title)
		}

		query = query.Find(&goods)

		jsonData, _ := json.Marshal(goods)

		cache.RedisDB.Set(l.ctx, "listGoods", jsonData, time.Hour*24)
	} else {
		json.Unmarshal([]byte(cacheData), &goods)
	}

	var listGoods []*productRpc.ListProduct
	for _, good := range goods {
		list := productRpc.ListProduct{
			Id:     int64(good.ID),
			Image:  good.Image,
			Title:  good.Title,
			Info:   good.Info,
			Price:  float32(good.Price),
			UserId: good.UserId,
		}
		listGoods = append(listGoods, &list)
	}

	return &productRpc.ListProductResponse{
		List: listGoods,
	}, nil
}
